<template>
  <div class="container">
    <div class="panel" :class="{ 'activeHide': isHideList }">
      <div class="title" v-show="$store.state.user?.role === 'ADMIN'">
        <img :src="require('./images/title.png')" /> &nbsp;&nbsp;
        <span>模型上传</span>
      </div>
      <br v-show="$store.state.user?.role === 'ADMIN'" />
      <!-- elementui写一个上传excel表单，填写模型编号 -->
      <el-form label-width="80px" size="small" v-show="$store.state.user?.role === 'ADMIN'">
        <el-form-item label="模型编号">
          <el-input v-model="modelCode" placeholder="请输入模型编号" size="small" clearable></el-input>
        </el-form-item>
        <el-form-item label="上传文件">
          <input type="file" id="file" accept=".xlsx,.xls,.csv" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">上传</el-button>
        </el-form-item>
      </el-form>

      <div class="title">
        <img :src="require('./images/title.png')" /> &nbsp;&nbsp;
        <span>模型查看</span>
      </div>
      <br />
      <!-- 写一个表单，有模型编码下拉，模型深度下拉，查看按钮 -->
      <el-form ref="form" :model="ruleForm" :rules="rules" label-width="80px" size="small">
        <el-form-item label="模型编号" prop="selectModelNum">
          <el-select v-model="ruleForm.selectModelNum" placeholder="请选择模型编号">
            <el-option v-for="(item, index) in model_num_list" :key="index" :label="item.model_num"
              :value="item.model_num"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模型深度" prop="selectModelDepth">
          <el-select v-model="ruleForm.selectModelDepth" placeholder="请选择模型深度">
            <el-option v-for="(item, index) in depth_list" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="属性字段" prop="selectModelAttr">
          <el-select v-model="ruleForm.selectModelAttr" placeholder="请选择模型属性">
            <el-option v-for="(item, index) in attr_list" :key="index" :label="item.name" :value="item.val"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="yuanshitu">原始数据</el-button>
          <el-button type="primary" @click="dengzhitu">等值图</el-button>
          <el-button type="primary" @click="kringtu">克里金插值</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="tixuanran">体渲染</el-button>
        </el-form-item>
        <el-form-item label="经度方向">
          <el-slider v-model="x_value" @change="cutX" :min="-0.5" :max="0.5" :step="0.01"></el-slider>
        </el-form-item>
        <el-form-item label="纬度方向">
          <el-slider v-model="y_value" @change="cutY" :min="-0.5" :max="0.5" :step="0.01"></el-slider>
        </el-form-item>
        <el-form-item label="高度方向">
          <el-slider v-model="z_value" @change="cutZ" :min="-0.5" :max="0.5" :step="0.01"></el-slider>
        </el-form-item>
      </el-form>

      <!-- <div class="title">
        <img :src="require('./images/title.png')" /> &nbsp;&nbsp;
        <span>三维模型展示</span>
      </div>
      <br />
      <el-form ref="form" :model="ruleForm" :rules="rules" label-width="80px" size="small">
        <el-form-item label="模型编号" prop="selectModelNum">
          <el-select v-model="ruleForm.selectModelNum" placeholder="请选择模型编号">
            <el-option v-for="(item, index) in model_num_list" :key="index" :label="item.model_num"
              :value="item.model_num"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          
        </el-form-item>
      </el-form> -->
    </div>
    <div class="legend">
      <img :src="require('./images/legend.jpg')" width="300" height="130" />
      <span style="    font-size: 18px;
    color: red;
    position: absolute;
    left: 0;
    right: 0;
    margin: auto;
    text-align: center;
    bottom: 30px;
">红色表示低速，蓝色表示高速</span>
    </div>
  </div>
</template>

<script>
let $ = window.$;
let kriging = window.kriging;
const { mars3d, turf } = window
let krigingLayer = null
const canvasMap = document.getElementById('canvasMap');
let graphicLayer = null;
export default {
  name: 'equipmentList',
  props: {
    map: {
      type: Object,
      default: () => { }
    }
  },
  data() {
    return {
      x_value: -0.5,
      y_value: -0.5,
      z_value: 0.5,
      fileList: [],
      model_num_list: [],
      modelCode: '',
      depth_list: [0, 5, 10, 15, 20, 30, 40, 'ALL'],
      attr_list: [{ name: '速度', val: 'vel' }, { name: '平均速度', val: 'avel' }, { name: '扰动百分比', val: 'pertub' }],
      ruleForm: {
        selectModelNum: '',
        selectModelDepth: '',
        selectModelAttr: '',
      },
      rules: {
        selectModelNum: [
          { required: true, message: '请选择模型编号', trigger: 'change' },
        ],
        selectModelDepth: [
          { required: true, message: '请选择模型深度', trigger: 'change' }
        ],
        selectModelAttr: [
          { required: true, message: '请选择模型属性', trigger: 'change' }
        ],
      },
      descData: {},

      searchText: '',
      xy_coor: '',
      res: [],
      res_temp: [],
      isHideList: false,
      selectItemRanking: '',
      tips: '',
    }
  },
  watch: {
    '$store.state.quxianCode': {
      handler() {
        // this.yuCe()
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.getModelNumList();
    graphicLayer = new mars3d.layer.GraphicLayer()
    this.map.addLayer(graphicLayer)
  },
  methods: {
    beforeUpload() {
      const isExcel = this.fileList[0].name.endsWith('.xlsx') || this.fileList[0].name.endsWith('.xls') || this.fileList[0].name.endsWith('.csv')
      if (!isExcel) {
        this.$message.error('请上传Excel格式文件')
        return false
      }
      return true
    },
    handleSuccess(res, file) {
      // 上传成功后，将文件名和文件内容保存到vuex中
      this.$store.commit('setUploadFile', { fileName: file.name, fileContent: res })
      this.$message.success('上传成功')
    },
    submitForm() {
      var fileInput = $('#file')[0];
      var file = fileInput.files[0];
      if (!file) {
        this.$message.warning("请先选择一个文件.");
        return;
      }
      // 判断是表格文件
      if (!/\.(xls|xlsx|csv)$/.test(file.name)) {
        this.$message.warning("请选择正确的表格文件！");
        return;
      }
      if (this.modelCode.trim() == '') {
        this.$message.warning("请输入模型编号！");
        return;
      }

      $.ajax({
        url: 'api/crud/query',
        type: 'POST',
        headers: {
          'Authorization': localStorage.getItem('token')
        },
        data: JSON.stringify({
          "sql": "select count(distinct model_num) as count from vs_model where model_num='" + this.modelCode + "'"
        }),
        contentType: 'application/json',
        success: function (res) {
          console.log(res);
          if (res.success) {
            if (res.data.body[0].count == 0) {
              var formData = new FormData();
              formData.append('file', file);
              formData.append('sql', 'insert into vs_model (lat,long,depth,vel,avel,pertub,model_num) values (? , ? , ? , ? , ? , ? , ?)');
              $.ajax({
                url: 'api/crud/upload2db',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false, // 告诉 jQuery 不要去设置 Content-Type 请求头 'application/x-www-form-urlencoded;charset=UTF-8',
                // dataType: 'json',
                success: function (res) {
                  console.log(res);
                  if (res === 'success') {
                    this.$message.info('添加成功', {
                      icon: 1,
                      time: 1000
                    }, function () {
                      // table.reload('userTable');
                    });
                  } else {
                    this.$message.info('添加成功', {
                      icon: 2,
                      time: 1000
                    });
                  }
                },
                error: function (err) {
                  console.log(err);
                  this.$message.info('请求失败，请稍后重试', {
                    icon: 2,
                    time: 1000
                  });
                }
              });
            } else {
              this.$message.info('项目别名已存在，不可用！')
            }

          } else {
            this.$message.info('query error')
          }
        },
        error: function (err) {
          console.log(err);
          this.$message.info('请求失败，请稍后重试', {
            icon: 2,
            time: 1000
          });
        }
      });

      // this.$refs.form.validate((valid) => {
      //   if (valid) {
      //     this.$message.success('上传成功')
      //     this.isHideList = true
      //   } else {
      //     this.$message.error('请检查输入项')
      //   }
      // })
    },
    getModelNumList() {
      this.axios.post('/crud/query', {
        sql: 'select distinct model_num from vs_model'
      }).then(res => {
        if (res.data.success) {
          this.model_num_list = res.data.data.body
        } else {
          this.model_num_list = []
        }
      })
    },
    dengzhitu() {
      console.log(this.ruleForm)
      if (this.ruleForm.selectModelDepth === 'ALL') {
        this.$message.warning('请选择具体的模型深度')
        return;
      }
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          let res = await this.axios.post('/crud/query', {
            sql: "select min(vel) as min_vel, max(vel) as max_vel, min(avel) as min_avel, max(avel) as max_avel, min(pertub) as min_pertub, max(pertub) as max_pertub from vs_model where model_num = '" + this.ruleForm.selectModelNum + "' and depth = '" + this.ruleForm.selectModelDepth + "';"
          })
          this.descData = res.data.data.body[0]
          // let sql = this.ruleForm.selectModelDepth === 'ALL' ? `select * from vs_model where model_num='${this.ruleForm.selectModelNum}'`:`select * from vs_model where model_num='${this.ruleForm.selectModelNum}' and depth='${this.ruleForm.selectModelDepth}'`
          this.axios.post('/crud/query', {
            sql: `select * from vs_model where model_num='${this.ruleForm.selectModelNum}' and depth='${this.ruleForm.selectModelDepth}'`
          }).then(res => {
            if (res.data.success) {
              this.res = res.data.data.body
              console.log(this.res)
              this.rendererCz(this.res, this.ruleForm.selectModelAttr);
            } else {
              this.$message.error('查询失败')
            }
          })
        } else {
          return false;
        }
      });
      // console.log(this.selectModelNum, this.selectModelDepth, this.selectModelAttr)
    },
    rendererCz(arr, field) {
      var colors = ['#006837', "#006837", '#00904d', "#1a9850", '#5ab054', "#66bd63", "#a6d96a", "#a6bd6a", "#d9ef8b",
        "#ffffbf", '#fef5a3', "#fee08b", '#fdc08e', "#fdae61", '#fb7966', "#f46d43", "#d73027", "#a50026", "#f40000"]
      // colors = [
      // '#006837','#007c42','#00904d','#1a9850','#2a9d58','#3aa360','#00a458','#4aa968','#5ab070','#6ab678',
      // '#7abd80','#8ac388','#9ac990','#aad098','#bad6a0','#cadba8','#dadcb0','#eae1b8','#f9f7c0','#ffffbf',
      // '#fef5a3','#fef287','#fef06b','#fefa4f','#fef733','#fee08b','#fedc95','#fdbd70','#fec99f','#fdd6bc',
      // '#fdc9ac','#feb5ad','#fdc08e','#fdbd9d','#fdb37f','#fdae61','#fd7d70','#fc7b6b','#fb7966','#fa7761',
      // '#f9755c','#f87357','#f77152','#f66f4d','#f56e48','#f46d43',"#d73027", "#a50026"]
      var breaks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
        25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 99] // 等值面的级数
      breaks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 99]
      var pointGrid = []

      function getColor(value) {
        for (var i = 0; i < breaks.length; i++) {
          if (breaks[i] === value) {
            return colors[i]
          }
        }
        return colors[0]
      }

      for (var i = 0, len = arr.length; i < len; i++) {
        var item = arr[i]
        pointGrid.push({
          type: "Feature",
          properties: {
            ...item,
            '_vel': (item.vel - this.descData.min_vel) / (this.descData.max_vel - this.descData.min_vel) * 10,
            '_avel': (item.avel - this.descData.min_avel) / (this.descData.max_avel - this.descData.min_avel) * 10,
            '_pertub': (item.pertub - this.descData.min_pertub) / (this.descData.max_pertub - this.descData.min_pertub) * 10,
          },
          geometry: {
            type: "Point",
            coordinates: [item.long, item.lat]
          }
        })
      }

      var points = {
        type: "FeatureCollection",
        features: pointGrid
      }

      console.log(this.descData, points)

      var geojsonPoly = turf.isobands(points, breaks, {
        zProperty: '_' + field
      })
      console.log(JSON.stringify(geojsonPoly))
      this.clearMyLayer()
      var geoJsonLayer = new mars3d.layer.GeoJsonLayer({
        id: 'layerDZM',
        name: "等值面",
        data: geojsonPoly,
        popup: "{_" + field + "}",
        symbol: {
          type: "polygonC",
          styleOptions: {
            fill: true, // 是否填充
            color: "#ffff00", // 颜色
            opacity: 1 // 透明度
          },
          callback: function (attr, styleOpt) {
            console.log(attr, styleOpt)
            // 得到点的权重，计算落在那个色度带
            var val = Number(attr['_' + field].split("-")[0] || 0)
            console.log(attr['_' + field].split("-")[0], val)
            var color = getColor(val)
            return {
              color: color
              // height: 0,
              // diffHeight: val * 10000
            }
          }
        }
      })
      this.map.addLayer(geoJsonLayer)

      // 等值线
      var geojsonLine = turf.isolines(points, breaks, {
        zProperty: '_' + field
      })


      // 进行平滑处理
      // var features = geojsonLine.features;
      // for (var i = 0; i < features.length; i++) {
      //     var _coords = features[i].geometry.coordinates;
      //     var _lCoords = [];
      //     for (var j = 0; j < _coords.length; j++) {
      //         var _coord = _coords[j];
      //         var line = turf.lineString(_coord);
      //         var curved = turf.bezierSpline(line);
      //         _lCoords.push(curved.geometry.coordinates);
      //     }
      //     features[i].geometry.coordinates = _lCoords;
      // }

      var layerDZX = new mars3d.layer.GeoJsonLayer({
        id: "layerDZX",
        name: "等值线",
        data: geojsonLine,
        popup: "{" + field + "}",
        symbol: {
          styleOptions: {
            width: 2, // 边框宽度
            color: "#000000", // 边框颜色
            opacity: 0.5, // 边框透明度
            clampToGround: false // 是否贴地
          }
        }
      })
      this.map.addLayer(layerDZX)
    },
    clearMyLayer() {
      this.map.viewer.entities.removeAll()
      this.map.removeLayer('layerDZM')
      this.map.removeLayer('layerDZX')
      this.clearKriging();
      graphicLayer && graphicLayer.clear();
      graphicLayer = null;
    },

    yuanshitu() {
      console.log(this.ruleForm)
      // if (this.ruleForm.selectModelDepth === 'ALL') {
      //   this.$message.warning('请选择具体的模型深度')
      //   return;
      // }
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          let sql = this.ruleForm.selectModelDepth === 'ALL' ? `select * from vs_model where model_num='${this.ruleForm.selectModelNum}'` : `select * from vs_model where model_num='${this.ruleForm.selectModelNum}' and depth='${this.ruleForm.selectModelDepth}'`
          this.axios.post('/crud/query', {
            sql: sql
          }).then(res => {
            if (res.data.success) {
              this.res = res.data.data.body || []
              this.clearMyLayer()
              this.res.forEach(point => {
                this.map.viewer.entities.add({
                  position: Cesium.Cartesian3.fromDegrees(point.long, point.lat, point.depth * 1000),
                  point: {
                    color: Cesium.Color.RED,
                    pixelSize: 8
                  },
                  label: {
                    text: `${this.ruleForm.selectModelAttr}: ${point[this.ruleForm.selectModelAttr]}`,
                    font: '12px Arial',
                    fillColor: Cesium.Color.BLUE,
                    outlineColor: Cesium.Color.BLACK,
                    outlineWidth: 2,
                    horizontalOrigin: Cesium.HorizontalOrigin.RIGHT,
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM
                  }
                });
              });
            } else {
              this.$message.error('查询失败')
            }
          })
        } else {
          return false;
        }
      });
    },
    kringtu() {
      console.log(this.ruleForm)
      if (this.ruleForm.selectModelDepth === 'ALL') {
        this.$message.warning('请选择具体的模型深度')
        return;
      }
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          let res = await this.axios.post('/crud/query', {
            sql: "select min(long) as min_long, max(long) as max_long, min(lat) as min_lat, max(lat) as max_lat, min(vel) as min_vel, max(vel) as max_vel, min(avel) as min_avel, max(avel) as max_avel, min(pertub) as min_pertub, max(pertub) as max_pertub from vs_model where model_num = '" + this.ruleForm.selectModelNum + "' and depth = '" + this.ruleForm.selectModelDepth + "';"
          })
          this.descData = res.data.data.body[0]
          // let sql = this.ruleForm.selectModelDepth === 'ALL' ? `select * from vs_model where model_num='${this.ruleForm.selectModelNum}'`:`select * from vs_model where model_num='${this.ruleForm.selectModelNum}' and depth='${this.ruleForm.selectModelDepth}'`
          this.axios.post('/crud/query', {
            sql: `select * from vs_model where model_num='${this.ruleForm.selectModelNum}' and depth='${this.ruleForm.selectModelDepth}'`
          }).then(res => {
            if (res.data.success) {
              this.res = res.data.data.body || []
              this.clearMyLayer()

              const n = this.res.length;
              const t = [];
              const x = [];
              const y = [];
              let colors = ["#00A600", "#01A600", "#03A700", "#04A700", "#05A800", "#07A800", "#08A900", "#09A900", "#0BAA00", "#0CAA00", "#0DAB00", "#0FAB00", "#10AC00", "#12AC00", "#13AD00", "#14AD00", "#16AE00", "#17AE00", "#19AF00", "#1AAF00", "#1CB000", "#1DB000", "#1FB100", "#20B100", "#22B200", "#23B200", "#25B300", "#26B300", "#28B400", "#29B400", "#2BB500", "#2CB500", "#2EB600", "#2FB600", "#31B700", "#33B700", "#34B800", "#36B800", "#37B900", "#39B900", "#3BBA00", "#3CBA00", "#3EBB00", "#3FBB00", "#41BC00", "#43BC00", "#44BD00", "#46BD00", "#48BE00", "#49BE00", "#4BBF00", "#4DBF00", "#4FC000", "#50C000", "#52C100", "#54C100", "#55C200", "#57C200", "#59C300", "#5BC300", "#5DC400", "#5EC400", "#60C500", "#62C500", "#64C600", "#66C600", "#67C700", "#69C700", "#6BC800", "#6DC800", "#6FC900", "#71C900", "#72CA00", "#74CA00", "#76CB00", "#78CB00", "#7ACC00", "#7CCC00", "#7ECD00", "#80CD00", "#82CE00", "#84CE00", "#86CF00", "#88CF00", "#8AD000", "#8BD000", "#8DD100", "#8FD100", "#91D200", "#93D200", "#95D300", "#97D300", "#9AD400", "#9CD400", "#9ED500", "#A0D500", "#A2D600", "#A4D600", "#A6D700", "#A8D700", "#AAD800", "#ACD800", "#AED900", "#B0D900", "#B2DA00", "#B5DA00", "#B7DB00", "#B9DB00", "#BBDC00", "#BDDC00", "#BFDD00", "#C2DD00", "#C4DE00", "#C6DE00", "#C8DF00", "#CADF00", "#CDE000", "#CFE000", "#D1E100", "#D3E100", "#D6E200", "#D8E200", "#DAE300", "#DCE300", "#DFE400", "#E1E400", "#E3E500", "#E6E600", "#E6E402", "#E6E204", "#E6E105", "#E6DF07", "#E6DD09", "#E6DC0B", "#E6DA0D", "#E6D90E", "#E6D710", "#E6D612", "#E7D414", "#E7D316", "#E7D217", "#E7D019", "#E7CF1B", "#E7CE1D", "#E7CD1F", "#E7CB21", "#E7CA22", "#E7C924", "#E8C826", "#E8C728", "#E8C62A", "#E8C52B", "#E8C42D", "#E8C32F", "#E8C231", "#E8C133", "#E8C035", "#E8BF36", "#E9BE38", "#E9BD3A", "#E9BC3C", "#E9BB3E", "#E9BB40", "#E9BA42", "#E9B943", "#E9B945", "#E9B847", "#E9B749", "#EAB74B", "#EAB64D", "#EAB64F", "#EAB550", "#EAB552", "#EAB454", "#EAB456", "#EAB358", "#EAB35A", "#EAB35C", "#EBB25D", "#EBB25F", "#EBB261", "#EBB263", "#EBB165", "#EBB167", "#EBB169", "#EBB16B", "#EBB16C", "#EBB16E", "#ECB170", "#ECB172", "#ECB174", "#ECB176", "#ECB178", "#ECB17A", "#ECB17C", "#ECB17E", "#ECB27F", "#ECB281", "#EDB283", "#EDB285", "#EDB387", "#EDB389", "#EDB38B", "#EDB48D", "#EDB48F", "#EDB591", "#EDB593", "#EDB694", "#EEB696", "#EEB798", "#EEB89A", "#EEB89C", "#EEB99E", "#EEBAA0", "#EEBAA2", "#EEBBA4", "#EEBCA6", "#EEBDA8", "#EFBEAA", "#EFBEAC", "#EFBFAD", "#EFC0AF", "#EFC1B1", "#EFC2B3", "#EFC3B5", "#EFC4B7", "#EFC5B9", "#EFC7BB", "#F0C8BD", "#F0C9BF", "#F0CAC1", "#F0CBC3", "#F0CDC5", "#F0CEC7", "#F0CFC9", "#F0D1CB", "#F0D2CD", "#F0D3CF", "#F1D5D1", "#F1D6D3", "#F1D8D5", "#F1D9D7", "#F1DBD8", "#F1DDDA", "#F1DEDC", "#F1E0DE", "#F1E2E0", "#F1E3E2", "#F2E5E4", "#F2E7E6", "#F2E9E8", "#F2EBEA", "#F2ECEC", "#F2EEEE", "#F2F0F0", "#F2F2F2"];
              // colors = ["#006837", "#1a9850", "#66bd63", "#a6d96a", "#d9ef8b", "#ffffbf", "#fee08b", "#fdae61", "#f46d43", "#d73027", "#a50026"];
              for (let i = 0; i < n; i++) {
                t.push(this.res[i].vel); // 权重值
                x.push(this.res[i].long); // x
                y.push(this.res[i].lat); // y
              }

              console.log(this.descData);
              // 定义插值范围
              const bounds = {
                // xMin: Math.min(...x) - 2,
                // xMax: Math.max(...x) + 2,
                // yMin: Math.min(...y) - 2,
                // yMax: Math.max(...y) + 2
                xMin: Math.min(...x),
                xMax: Math.max(...x),
                yMin: Math.min(...y),
                yMax: Math.max(...y)
              };

              console.log(bounds);

              // 训练克里金模型
              const variogram = kriging.train(t, x, y, "exponential", 0, 100);

              // 生成网格
              const grid = kriging.grid([[[bounds.xMin, bounds.yMin], [bounds.xMin, bounds.yMax], [bounds.xMax, bounds.yMax], [bounds.xMax, bounds.yMin], [bounds.xMin, bounds.yMin]]], variogram, (bounds.yMax - bounds.yMin) / 500);

              // 绘制插值结果到 canvas
              kriging.plot(canvasMap, grid, [bounds.xMin, bounds.xMax], [bounds.yMin, bounds.yMax], colors);

              // 将 canvas 转换为图像并添加到 Cesium 地图上
              const imageryLayer = new Cesium.SingleTileImageryProvider({
                url: canvasMap.toDataURL("image/png"),
                rectangle: Cesium.Rectangle.fromDegrees(bounds.xMin, bounds.yMin, bounds.xMax, bounds.yMax)
              });

              krigingLayer = this.map.viewer.imageryLayers.addImageryProvider(imageryLayer);
            } else {
              this.$message.error('查询失败')
            }
          })
        } else {
          return false;
        }
      });
    },
    clearKriging() {
      if (krigingLayer) {
        this.map.viewer.imageryLayers.remove(krigingLayer);
        krigingLayer = null;
      }
    },
    async tixuanran() {
      console.log(this.ruleForm)
      if (!this.ruleForm.selectModelNum) {
        this.$message.warning('请选择具体的模型')
        return;
      }
      let res = await this.axios.post('/crud/query', {
        sql: "select min(long) as min_long, max(long) as max_long, min(lat) as min_lat, max(lat) as max_lat, min(vel) as min_vel, max(vel) as max_vel, min(avel) as min_avel, max(avel) as max_avel, min(pertub) as min_pertub, max(pertub) as max_pertub from vs_model where model_num = '" + this.ruleForm.selectModelNum + "';"
      })
      this.descData = res.data.data.body[0]
      // let sql = this.ruleForm.selectModelDepth === 'ALL' ? `select * from vs_model where model_num='${this.ruleForm.selectModelNum}'`:`select * from vs_model where model_num='${this.ruleForm.selectModelNum}' and depth='${this.ruleForm.selectModelDepth}'`
      this.axios.post('/crud/query', {
        sql: `select * from vs_model where model_num='${this.ruleForm.selectModelNum}'`
      }).then(res => {
        console.log(res)
        const colors = [
          // "rgb(0,0,0,0)",
          // "rgb(170,36,250)",
          // "rgba(212,142,254,0.13)",
          // "rgba(238,2,48,0.12)",
          // "rgba(254,100,92,0.11)",
          // "rgba(254,172,172,0.1)",
          // "rgba(140,140,0,0.09)",
          // "rgba(200,200,2,0.08)",
          // "rgba(252,244,100,0.07)",
          // "rgba(16,146,26,0.06)",
          // "rgba(0,234,0,0.05)",
          // "rgba(166,252,168,0.04)",
          // "rgba(30,38,208,0.03)",
          // "rgba(122,114,238,0.02)",
          // "rgba(192,192,254,0.01)"
          "rgb(238,2,48,0.5)",
          "rgba(236,80,48,0.5)",
          "rgba(254,100,92,0.5)",
          "rgb(170,36,250,0.5)",
          "rgba(212,142,254,0.5)",
          "rgba(254,172,172,0.5)",
          "rgba(252,244,100,0.5)",
          "rgba(200,200,2,0.5)",
          "rgba(140,140,0,0.5)",
          "rgba(16,146,26,0.5)",
          "rgba(0,234,0,0.5)",
          "rgba(166,252,168,0.5)",
          "rgba(30,38,208,0.5)",
          "rgba(122,114,238,0.5)",
          "rgba(192,192,254,0.5)"
        ]
        // const steps = [0, 0.1, 0.2, 0.3, 1.2, 1.5, 1.8, 2.1, 2.4, 2.7, 3, 3.5, 4, 5]
        let steps = [0.2, 3, 3.1, 3.2, 3.3, 3.4, 3.5, 3.55, 3.6, 3.7, 3.75, 3.8, 4, 4.8]
        let rows = 19
        let cols = 19
        let heights = 7
        let field = 'vel'
        switch (this.ruleForm.selectModelNum) {
          case 'a01':
            steps = [0.2, 3, 3.1, 3.2, 3.3, 3.4, 3.5, 3.55, 3.6, 3.7, 3.75, 3.8, 4, 4.8]
            rows = 19
            cols = 19
            heights = 7
            this.descData.min_long = 112.07 // 最小经度（度数，-180-180）
            this.descData.max_long = 114.51 // 最大经度（度数，-180-180）
            this.descData.min_lat = 39.8 // 最小纬度（度数，-90-90）
            this.descData.max_lat = 40.45
            break;
          case 'a02':
            steps = [2.7, 2.8, 2.9, 3.0, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 4.15]
            rows = 7
            cols = 11
            heights = 6
            field = 'avel'
            break;
          case 'a04':
            // steps = [4, 4.15, 4.25, 4.3, 4.5, 4.7, 4.9, 5, 5.2, 5.5, 5.8, 6, 7, 8];
            steps = [1, 1.5, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3.0, 3.1, 3.2]
            rows = 7
            cols = 6
            heights = 6
            field = 'avel'
            break;
          case 'a03':
            // steps = [4, 4.15, 4.25, 4.3, 4.5, 4.7, 4.9, 5, 5.2, 5.5, 5.8, 6, 7, 8];
            steps = [2.7, 2.82, 2.94, 3.06, 3.18, 3.3, 3.42, 3.54, 3.66, 3.78, 3.9, 4.12, 4.3, 4.45]
            rows = 5
            cols = 5
            heights = 6
            field = 'vel'
            break;
          default:
            break;
        }


        // 创建气象数据体渲染模型
        const volumeCloud = new mars3d.graphic.VolumeCloud({
          data: {
            // rows: data.rows, // 行网格数
            // cols: data.cols, // 列网格数
            // heights: data.heights, // 高网格数
            // values: data.values, // 3D 数据集数组, 数组长度应该是 rows*cols*heights, 顺序为： [height1-row1-col1, height1-row1-col2,…… ,height1-row2-col1, height1-row2-col2,…… ,height2-row1-col1, height2-row1-col2,……]

            // xmin: data.xmin, // 最小经度（度数，-180-180）
            // xmax: data.xmax, // 最大经度（度数，-180-180）
            // ymin: data.ymin, // 最小纬度（度数，-90-90）
            // ymax: data.ymax, // 最大纬度（度数，-90-90）
            // zmin: data.zmin, // 最小高度
            // zmax: data.zmax // 最大高度
            rows, // 行网格数
            cols, // 列网格数
            heights, // 高网格数
            values: res.data.data.body.map(item => item[field]), // 3D 数据集数组, 数组长度应该是 rows*cols*heights, 顺序为： [height1-row1-col1, height1-row1-col2,…… ,height1-row2-col1, height1-row2-col2,…… ,height2-row1-col1, height2-row1-col2,……]

            xmin: this.descData.min_long, // 最小经度（度数，-180-180）
            xmax: this.descData.max_long, // 最大经度（度数，-180-180）
            ymin: this.descData.min_lat, // 最小纬度（度数，-90-90）
            ymax: this.descData.max_lat, // 最大纬度（度数，-90-90）
            zmin: 0, // 最小高度
            zmax: 40000 // 最大高度
          },
          steps,
          colors
          // flyTo: true
        })
        // graphicLayer.clear()
        this.clearMyLayer()
        if (!graphicLayer) {
          graphicLayer = new mars3d.layer.GraphicLayer()
          this.map.addLayer(graphicLayer)
        }
        graphicLayer.addGraphic(volumeCloud)
      })
      // 显示边界，方便对比测试
      //   showDebuggerRectangleOutline(volumeCloud)

      // setInterval(() => {
      //   for (let index = 0, len = data.values.length; index < len; index++) {
      //     if (data.values[index] > 20) {
      //       data.values[index] = Math.abs(data.values[index] * 1.001)
      //     }
      //   }

      //   volumeCloud.updateData({
      //     rows: data.rows, // 行网格数
      //     cols: data.cols, // 列网格数
      //     heights: data.heights, // 高网格数
      //     values: data.values // 3D 数据集数组, 数组长度应该是 rows*cols*heights
      //   })
      // }, 1000)

      // 显示Rectangle矩形体边界，方便对比测试
    },
    showDebuggerRectangleOutline(volumeCloud) {
      const boxOutlineInstance = new Cesium.GeometryInstance({
        geometry: new Cesium.RectangleOutlineGeometry({
          ellipsoid: Cesium.Ellipsoid.WGS84,
          rectangle: volumeCloud._rectangle,
          height: volumeCloud.options.data.zmin,
          extrudedHeight: volumeCloud.options.data.zmax
        }),
        attributes: {
          color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.WHITE)
        }
      })

      this.map.scene.primitives.add(
        new Cesium.Primitive({
          geometryInstances: boxOutlineInstance,
          appearance: new Cesium.PerInstanceColorAppearance({
            flat: true
          })
        })
      )
    },
    cutX(value) {
      console.log(value, graphicLayer, graphicLayer.graphics)
      if (graphicLayer.graphics[0] && graphicLayer.graphics[0].type === "volumeCloud") {
        graphicLayer.graphics[0].xCut = value
      }
    },
    cutY(value) {
      if (graphicLayer.graphics[0] && graphicLayer.graphics[0].type === "volumeCloud") {
        graphicLayer.graphics[0].yCut = value
      }
    },
    cutZ(value) {
      if (graphicLayer.graphics[0] && graphicLayer.graphics[0].type === "volumeCloud") {
        graphicLayer.graphics[0].zCut = value
      }
    }
  },
}
</script>

<style scoped>
.container {
  z-index: 999;
  position: fixed;
  top: 100px;
  left: 20px;
  width: 400px;
  height: calc(800px);
  /*  - 135px */
  .legend {
    position: absolute;
    bottom: 0px;
    left: 410px;
    /* width: 200px;
    height: 100px; */
  }
  .panel {
    background-color: rgba(4, 19, 30, 0.5);
    border-radius: 8px;
    padding: 4px 10px;
    display: flex;
    align-items: center;
    flex-direction: column;
    border: 2px solid #2A748A;
    color: #fff;
    height: calc(100% - 32px);
    /* 抽屉效果 */
    transition: transform 0.5s ease-in-out;

    &.activeHide {
      transform: translateX(400px);
    }

    .title {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      width: 100%;
      font-size: 18px;
      height: 35px;
      line-height: 35px;
      border-bottom: 1px solid #2A748A;

      img {
        width: 16px;
      }
    }

    .search-panel {
      margin-top: 10px;
      width: 100%;
      position: relative;

      img {
        position: absolute;
        left: 8px;
        top: 8px;
        width: 16px;
      }

      input {
        height: 30px;
        display: block;
        width: 308px;
        border-radius: 30px;
        background: rgba(64, 237, 255, 0.2);
        border: 0;
        padding-left: 30px;
        color: #fff;

        &:focus {
          outline: none;
          color: #fff;
          caret-color: rgba(64, 237, 255, 0.5);
        }
      }
    }

    .item-title {
      width: 100%;
      display: flex;
      margin: 5px 0;
      padding: 2px 0;
      justify-content: space-between;
      align-items: center;
      cursor: pointer;

      &.active {
        background-color: rgba(64, 237, 255, 0.2);
      }

      .item-left {
        font-size: 16px;
        width: 200px;
        text-align: left;
      }

      .item-middle {
        font-size: 14px;
        width: 50px;
        display: flex;
        justify-content: flex-start;
        align-items: center;
      }

      .item-right {
        font-size: 14px;
        font-weight: bold;
        width: 50px;
        text-align: center;
      }
    }

    .list-content {
      padding-left: 10px;
      overflow-y: auto;

      .item {
        width: 100%;
        display: flex;
        margin: 5px 0;
        padding: 2px 0;
        justify-content: space-between;
        align-items: center;
        cursor: pointer;

        &.active {
          background-color: rgba(64, 237, 255, 0.2);
        }

        .item-left {
          font-size: 16px;
          width: 200px;
          text-align: left;
        }

        .item-middle {
          font-size: 14px;
          width: 50px;
          display: flex;
          justify-content: flex-start;
          align-items: center;
        }

        .item-right {
          font-size: 14px;
          font-weight: bold;
          width: 50px;
          text-align: center;
          background-color: #fff;

          &.alarm-level-0 {
            color: #FF0100;
          }

          &.alarm-level-1 {
            color: #ff8100;
          }

          &.alarm-level-2 {
            color: #fefe00;
          }

          &.alarm-level-3 {
            color: #98cc00;
          }

          &.alarm-level-4 {
            color: #058200;
          }
        }
      }

    }

    /* 修改滚动条样式 */
    ::-webkit-scrollbar {
      width: 5px;
      height: 5px;
    }

    ::-webkit-scrollbar-thumb {
      background-color: #20edde;
      border-radius: 2px;
    }

    ::-webkit-scrollbar-track {
      /* background-color: #081D32; */
      /* border-radius: 2px; */
    }
  }

  /* 按钮 */
  .btn-panel {
    position: absolute;
    right: 100%;
    top: 50%;
    background: rgba(4, 19, 30, 0.5);
    width: 16px;
    height: 32px;
    line-height: 32px;
    text-align: center;
    border-radius: 18px 0 0 18px;
    cursor: pointer;
    transition: transform 0.5s ease-in-out;

    &.activeHide {
      transform: translateX(360px);
    }
  }

}
</style>